<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form
        ref="formRef"
        v-loading="formLoading || keyLoading"
        :model="formData"
        :rules="formRules"
        label-width="80px"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="用户昵称" prop="nickname">
            <el-input v-model="formData.nickname" placeholder="请输入用户昵称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="归属部门" prop="deptId">
            <el-tree-select
                v-model="formData.deptId"
                :data="deptList"
                :props="defaultProps"
                check-strictly
                node-key="id"
                placeholder="请选择归属部门"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="手机号码" prop="mobile">
            <el-input v-model="formData.mobile" maxlength="11" placeholder="请输入手机号码" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="formData.email" maxlength="50" placeholder="请输入邮箱" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item v-if="formData.id === undefined" label="用户名称" prop="username">
            <el-input v-model="formData.username" placeholder="请输入用户名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item v-if="formData.id === undefined || formData.password" label="用户密码" prop="password">
            <el-input
                v-model="formData.password"
                placeholder="请输入用户密码"
                show-password
                type="password"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="用户性别">
            <el-select v-model="formData.sex" placeholder="请选择">
              <el-option
                  v-for="dict in getIntDictOptions(DICT_TYPE.SYSTEM_USER_SEX)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="岗位">
            <el-select v-model="formData.postIds" multiple placeholder="请选择">
              <el-option
                  v-for="item in postList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id!"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注">
            <el-input v-model="formData.remark" placeholder="请输入内容" type="textarea" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading || keyLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { CommonStatusEnum } from '@/utils/constants'
import { defaultProps, handleTree } from '@/utils/tree'
import * as PostApi from '@/api/system/post'
import * as DeptApi from '@/api/system/dept'
import * as UserApi from '@/api/system/user'
import { SecurityApi } from '@/api/system/security'
import { FormRules } from 'element-plus'
import JSEncrypt from 'jsencrypt'

defineOptions({ name: 'SystemUserForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

// 弹窗核心状态
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const keyLoading = ref(false) // 获取公钥加载状态
const formType = ref('') // create/update

// 加密相关
const publicKey = ref('') // RSA公钥
const encryptor = new JSEncrypt()

// 表单数据
const formData = ref({
  nickname: '',
  deptId: '',
  mobile: '',
  email: '',
  id: undefined,
  username: '',
  password: '',
  sex: undefined,
  postIds: [],
  remark: '',
  status: CommonStatusEnum.ENABLE,
  roleIds: []
})

// 表单校验规则
const formRules = reactive<FormRules>({
  username: [{ required: true, message: '用户名称不能为空', trigger: 'blur' }],
  nickname: [{ required: true, message: '用户昵称不能为空', trigger: 'blur' }],
  password: [
    { required: (() => formData.value.id === undefined || formData.value.password) as any,
      message: '用户密码不能为空',
      trigger: 'blur'
    }
  ],
  email: [
    {
      type: 'email',
      message: '请输入正确的邮箱地址',
      trigger: ['blur', 'change']
    }
  ],
  mobile: [
    {
      pattern: /^(?:(?:\+|00)86)?1(?:3[\d]|4[5-79]|5[0-35-9]|6[5-7]|7[0-8]|8[\d]|9[189])\d{8}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur'
    }
  ]
})

// 其他依赖数据
const formRef = ref()
const deptList = ref<Tree[]>([])
const postList = ref([] as PostApi.PostVO[])

/**
 * 获取RSA公钥
 */
const fetchPublicKey = async () => {
  if (publicKey.value) return true // 已获取则直接返回
  try {
    keyLoading.value = true
    const res = await SecurityApi.getPublicKey()
    publicKey.value = res.publicKey
    encryptor.setPublicKey(publicKey.value)
    return true
  } catch (error) {
    message.error('获取加密公钥失败，请重试')
    return false
  } finally {
    keyLoading.value = false
  }
}

/**
 * RSA加密数据
 * @param data 待加密数据
 */
const encryptPassword = (data: string) => {
  if (!publicKey.value) throw new Error('公钥不存在，无法加密')
  return encryptor.encrypt(data) || ''
}

/**
 * 打开弹窗
 * @param type 操作类型 create/update
 * @param id 用户ID（更新时必填）
 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()

  // 加载基础数据（部门、岗位）
  const [deptRes, postRes] = await Promise.all([
    DeptApi.getSimpleDeptList(),
    PostApi.getSimplePostList()
  ])
  deptList.value = handleTree(deptRes)
  postList.value = postRes

  // 新增时提前获取公钥
  if (type === 'create') {
    await fetchPublicKey()
  }

  // 更新时加载用户数据
  if (id) {
    formLoading.value = true
    try {
      const userData = await UserApi.getUser(id)
      formData.value = { ...userData, password: '' } // 清空密码，避免明文展示
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open })

/**
 * 提交表单
 */
const emit = defineEmits(['success'])
const submitForm = async () => {
  // 表单校验
  if (!formRef.value) return
  await formRef.value.validate()

  formLoading.value = true
  try {
    const submitData = { ...formData.value } as UserApi.UserVO

    // 密码加密处理（新增必加密，更新有密码才加密）
    if (submitData.password) {
      // 确保公钥已获取
      if (!await fetchPublicKey()) {
        throw new Error('加密公钥获取失败，无法提交')
      }
      // 加密密码
      const encryptedPwd = encryptPassword(submitData.password)
      if (!encryptedPwd) throw new Error('密码加密失败')
      submitData.password = encryptedPwd
    }

    // 提交请求
    if (formType.value === 'create') {
      await UserApi.createUser(submitData)
      message.success(t('common.createSuccess'))
    } else {
      await UserApi.updateUser(submitData)
      message.success(t('common.updateSuccess'))
    }

    // 关闭弹窗并通知父组件
    dialogVisible.value = false
    emit('success')
  } catch (error) {
    console.error('表单提交失败:', error)
  } finally {
    formLoading.value = false
  }
}

/**
 * 重置表单
 */
const resetForm = () => {
  formData.value = {
    nickname: '',
    deptId: '',
    mobile: '',
    email: '',
    id: undefined,
    username: '',
    password: '',
    sex: undefined,
    postIds: [],
    remark: '',
    status: CommonStatusEnum.ENABLE,
    roleIds: []
  }
  formRef.value?.resetFields()
  publicKey.value = '' // 重置公钥
}
</script>
